package com.zxyankh.raft.controller;

import com.alibaba.fastjson.JSON;
import com.zxyankh.common.dto.ResponseDto;
import com.zxyankh.raft.context.ServerContext;
import com.zxyankh.raft.service.RaftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description: 处理客户端请求的Controller
 * 返回信息： code为200表示请求成功，data为返回内容；
 * code为300表示请求需要重新发给data指定的地址
 *
 * @author ankh
 * @since 13.08.2017
 */
@RestController("raft")
public class RaftController {

    @Autowired
    private RaftService raftService;

    /**
     * Description: 添加指令
     *
     * @param command 指令
     * @return 如果该服务实例不是Leader 则返回Leader的地址; 否则返回成功
     */
    @RequestMapping(value = "/add/{command:.*}", method = RequestMethod.PUT)
    public ResponseDto addCommand(@PathVariable("command") String command) {
        if (!ServerContext.isLeader()) {
            return new ResponseDto(300, ServerContext.getLeaderHttpAddress());
        }
        raftService.addCommand(command);
        return new ResponseDto(200, "success");
    }

    /**
     * Description: 查询指定index的指令
     *
     * @param index 指定的index
     * @return 如果该服务实例不是Leader 则返回Leader的地址;
     * 如果存在指定index的指令则返回指定index的指令, 否则返回null
     */
    @RequestMapping(value = "/get/{index}", method = RequestMethod.GET)
    public ResponseDto getCommand(@PathVariable("index") Integer index) {
        if (!ServerContext.isLeader()) {
            return new ResponseDto(300, ServerContext.getLeaderHttpAddress());
        }
        return new ResponseDto(200, JSON.toJSONString(raftService.getCommand(index)));
    }
}
